package companyTest.zhongan;

import java.util.*;

public class Solution {
    public boolean canFinish (int numCourses, int[][] prerequisites) {
        // write code here
        //e表示边
        List<List<Integer>>biAns=new ArrayList<>();
        //保存每个节点的入度
        int []ruDu=new int[numCourses];
        //给每个List代表当前节点的入度集合
        for (int i = 0; i < numCourses; i++) {
            biAns.add(new ArrayList<>());
        }
        for (int[] prerequisite : prerequisites) {
            int pre=prerequisite[1];
            int now=prerequisite[0];
            ruDu[now]++;
            biAns.get(now).add(pre);
        }
        Queue<Integer>queue=new ArrayDeque<>();
        for (int i = 0; i < biAns.size(); i++) {
           if (ruDu[i]==0)queue.offer(i);
        }
        int count=0;
        while (!queue.isEmpty()){
            Integer node=queue.poll();
            count++;
            for (int i = 0; i < biAns.size(); i++) {
                List<Integer>bian=biAns.get(i);
                if (bian.contains(node)){
                    ruDu[i]--;
                    if (ruDu[i]==0)queue.offer(i);
                }
            }
        }
        return count==numCourses;
    }
}
